#pragma once
#include <iostream>
#include <string>
#include <functional>
#include "Log.hpp"

class Connection;
class TcpServer;
using func_t = std::function<void(Connection*)>;

//一个连接，也就是一个文件描述发，他也就对应着他的缓冲区
class Connection{
public:
    Connection(int sockfd,uint32_t event,TcpServer *R):_sockfd(sockfd),_events(event),_R(R)
    {}
    ~Connection(){}

    int SockFD()
    {
        return _sockfd;
    }

    int SockEvent()
    {
        return _events;
    }

    void RegisterFunc(func_t recver,func_t sender,func_t excepter)
    {
        _recver = recver;
        _sender = sender;
        _excepter = excepter;
    }

    void AddBuffer(const std::string& buffer)
    {
        _inbuffer += buffer;
    }

    std::string& InBuffer()
    {
        return _inbuffer;
    }
    std::string& OutBuffer()
    {
        return _outbuffer;
    }

    void AddOutBuffer(const std::string& buffer)
    {
        _outbuffer += buffer;
    }

    bool OutBufferEmpty()
    {
        return _outbuffer.empty();
    }

    void SetEvent(uint32_t event)
    {
        _events = event;//修改连接里面的event
    }

    void Close()
    {
        ::close(_sockfd);
    }
private:
    int _sockfd;//文件描述符

    //对应的缓冲区
    std::string _inbuffer;
    std::string _outbuffer;

//当前连接要处理的事件
    uint32_t _events;

public://就不再封装了，否则有点难看
    func_t _recver;
    func_t _sender;
    func_t _excepter;
//TcpServer的回指指针
    TcpServer* _R;//
    //设置对应的回调函数
};

class ConnectionFactory{
public:
    static Connection* BuildListenConnection(int listensock,func_t recver,uint32_t events,TcpServer* R)//连接工厂
    {
        Connection* conn = new Connection(listensock,events,R);
        conn->RegisterFunc(recver,nullptr,nullptr);
        return conn;
    }

    static Connection* BuildNormalConnection(int listensock,func_t recver,func_t sender,func_t excepter,uint32_t events,TcpServer *R)
    {
        Connection* conn = new Connection(listensock,events,R);
        conn->RegisterFunc(recver,sender,excepter);
        return conn;
    }
};